#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import os
import time

import cv2
import numpy as np

from matplotlib import pyplot as plt
import re
import subprocess

import time
import mijing_cut_card as cut_card
from mijing_tesseract import get_enemy_hp

from log import get_logger

logger = get_logger(__name__, log_to_file=True)

imageFolder = "mijing2"

giveUpFlag = False


def get_screenshot(i):
    # name = '{:05d}_{}'.format(i, int(time.time()))
    name = '{:05d}'.format(i)
    os.system('adb shell screencap -p /sdcard/book/image/{}.png'.format(name))
    os.system('adb pull /sdcard/book/image/{}.png {}/{}.png'.format(name, imageFolder, name))
    os.system('adb shell rm /sdcard/book/image/{}.png'.format(name))
    return name


# def get_screenshot_static():
#     res = os.system('adb shell screencap -p /sdcard/book/image/img.png')
#     if res == 0:
#         res = os.system(
#             'adb pull /sdcard/book/image/img.png /home/liusen/IdeaWorkspace/wechat-jump/mijing2/img.png'.format(
#                 imageFolder))
#         if res == 0:
#             os.system('adb shell rm /sdcard/book/image/img.png')
#             if res == 0:
#                 return cv2.imread('/home/liusen/IdeaWorkspace/wechat-jump/mijing2/img.png')


# def get_screenshot_static():
#     res = os.system('/home/liusen/IdeaWorkspace/wechat-jump/ScreenCap.sh')
#     time.sleep(0.1)
#     if res == 0:
#         return cv2.imread('/home/liusen/IdeaWorkspace/wechat-jump/mijing2/img.png')

def get_screenshot_static():
    proc = subprocess.Popen(["/home/liusen/var/android-sdk-linux/platform-tools/adb shell screencap -p"], stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
    (out, err) = proc.communicate()
    if err:
        logger.debug(err.decode())
    if proc.returncode == 0:
        try:
            return cv2.imdecode(np.frombuffer(out, dtype=np.uint8), cv2.IMREAD_COLOR)
        except Exception as e:
            logger.error('img parse error')
            return


def click(location):
    cmd = 'adb shell input swipe %s %s %s %s 100' % (location[0], location[1], location[0], location[1])
    logger.debug('%s' % (cmd))
    os.system(cmd)


def click2(location):
    cmd = 'adb shell input swipe %s %s %s %s 300' % (location[0], location[1], location[2], location[3])
    logger.debug('%s' % (cmd))
    os.system(cmd)


def pascalToCamel(x):
    s = re.sub('_([a-z])', lambda match: match.group(1).upper(), x)
    return s[:1].upper() + s[1:]


def camelToPascal(x):
    s = re.sub('([a-zA-Z])([A-Z])', lambda match: match.group(1).lower() + "_" + match.group(2).lower(), x)
    return s[:1].lower() + s[1:]


images = {}

for (root, dirs, files) in os.walk('/home/liusen/IdeaWorkspace/wechat-jump/mijing3'):
    for item in files:
        filePath = os.path.join(root, item)
        s = os.path.splitext(item)[0]
        images[s] = cv2.cvtColor(cv2.imread(filePath), cv2.COLOR_BGR2GRAY)
        print('prepare image : ' + s)

location = {
    '01': [654, 678, 168, 186],
    '02': [654, 678, 168, 186],
    '03': [654, 678, 168, 186],
    '04': [654, 678, 168, 186],
    '05': [654, 678, 168, 186],
    '06': [654, 678, 168, 186],
    '07': [654, 678, 168, 186],
    '08': [654, 678, 168, 186],
    '09': [654, 678, 168, 186],
    'card_champion': [350, 386, 86, 156],
    'daily_task': [124, 156, 575, 705],
    'main_page': [382, 403, 417, 467],
    'match': [643, 670, 604, 674],
    'confirm': [616, 642, 598, 679],
    'end_round': [639, 698, 1188, 1239],
    'menu': [10, 70, 10, 70],
    'give_up': [276, 300, 609, 672],
    'click_to_continue': [666, 695, 587, 690],
    'participate_award': [88, 140, 545, 728],
    'log_back_in': [449, 481, 586, 692],
    'enter_game': [545, 578, 584, 693],
    'enter_round_2': [596, 614, 1196, 1231],
    'select_offensive_card': [35, 104, 551, 724],
    'select_defensive_card': [35, 104, 551, 724],
    'select_card': [115, 148, 514, 763],
    'level_1': [312, 387, 329, 408],
    'level_2': [312, 387, 329, 408],
    'level_3': [312, 387, 329, 408],
    'level_4': [312, 387, 329, 408],
    'level_5': [312, 387, 329, 408]
}


def detectImage(img, key, saveFlag=True, min=-1, max=-1):
# def detectImage(img, key, saveFlag=False, min=-1, max=-1):
    if key is None or key == '':
        plt.imshow(img), plt.show()
        return False

    # img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    [a, b, c, d] = location[key]
    img = img[a:b, c:d]

    if min != -1 and max != -1:
        FILTER_MIN = np.array([min], np.uint8)
        FILTER_MAX = np.array([max], np.uint8)
        frame_threshed = cv2.inRange(img, FILTER_MIN, FILTER_MAX)
        img = cv2.bitwise_or(img, img, mask=frame_threshed)

    if saveFlag:
        cv2.imwrite('/home/liusen/IdeaWorkspace/wechat-jump/mijing3/{}.png'.format(key), img)
        return False

    template = images[key]

    res = cv2.matchTemplate(img, template, cv2.TM_CCOEFF_NORMED)
    logger.debug("{} match value : {}".format(key, res[0][0]))

    factor = 0.93
    if key == 'end_round':
        factor = 0.75
    if key == 'enter_round_2':
        factor = 0.5
    elif key == 'click_to_continue':
        factor = 0.88
    # loc = np.where(res >= factor)
    # if len(list(zip(*loc[::-1]))) == 1:
    if res[0][0] >= factor:
        return True
    else:
        return False


class BattleHandler(object):
    def __init__(self):
        self.battleStage = 0
        self.notInBattleTime = 0

    def processBegin(self):
        if self.notInBattleTime >= 1:
            self.battleStage = 0
        self.notInBattleTime += 1
        logger.debug("battleStage : {}  notInBattleTime : {}".format(self.battleStage, self.notInBattleTime))
        pass

    def handleBattle(self, img, grey):
        self.notInBattleTime = 0

        if self.battleStage == 0:
            click([70, 483])
            # time.sleep(0.1)
            click([70, 380])
            # time.sleep(0.1)
            for i in range(900, 400, -90):
                if i == 630:
                    click2([i, 650, 1062, 498])
                    # time.sleep(0.1)
                click2([i, 650, 1062, 498])
                # time.sleep(0.1)

        if self.battleStage == 1:
            for i in range(250, 1100, 110):
                click2([i, 480, 655, 130])

        if self.battleStage >= 2:
            click([1188, 639])
            # time.sleep(0.1)
            click([1188, 639])
            time.sleep(2)

        # 处理卡牌放大
        # click([1188, 551])

        self.battleStage += 1
        pass


battleHandler = BattleHandler()


def check_img(img):
    return img.shape == (720, 1280, 3) or img.shape == (1080, 2160, 3)


def test():
    global giveUpFlag
    for i in range(100000):
        logger.debug('-----start handle process-----')
        start_time = time.time()
        img = get_screenshot_static()

        logger.debug('screenshot time : {} second'.format(time.time() - start_time))
        if img is not None and check_img(img):
            # print(grey.shape)
            battleHandler.processBegin()
            grey = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
            if grey.shape[0] == 1280:
                logger.debug('当前为横屏模式...')
                continue
            if detectImage(grey, 'log_back_in'):
                logger.debug('重新登录')
                click([586, 449])
                time.sleep(2)
                continue
            if detectImage(grey, 'enter_game'):
                logger.debug('进入游戏')
                click([584, 545])
                time.sleep(1)
                continue
            if detectImage(grey, 'click_to_continue'):
                logger.debug('继续游戏')
                click([587, 666])
                time.sleep(0.1)
                continue
            if detectImage(grey, 'participate_award'):
                logger.debug('参与奖励')
                click([587, 666])
                time.sleep(0.1)
                continue
            # 如果有日常任务就点关闭
            if detectImage(grey, 'daily_task'):
                logger.debug('关闭日常任务')
                click([1018, 143])
                time.sleep(1)
                continue
            # 如果是主页面 就点击进入对决模式
            if detectImage(grey, 'main_page'):
                logger.debug('进入对决模式')
                click([637, 271])
                time.sleep(1)
                continue
            if detectImage(grey, 'card_champion'):
                logger.debug('遇到擂主了，认真玩吧')
                time.sleep(3000)
                # sys.exit(0)
                continue
            if detectImage(grey, 'match'):
                logger.debug('匹配战斗')
                if detectImage(grey, 'level_3', saveFlag=False, min=250, max=255) or \
                        detectImage(grey, 'level_2', saveFlag=False, min=250, max=255) or \
                        detectImage(grey, 'level_1', saveFlag=False, min=250, max=255):
                    logger.debug('放弃下一场战斗')
                    giveUpFlag = True
                else:
                    logger.debug('正常准备下一场战斗')
                    giveUpFlag = False
                click([634, 653])
                time.sleep(3)
                continue
            if detectImage(grey, 'confirm') and detectImage(grey, 'select_card', min=250, max=255):
                res, location = cut_card.handle_select_card(img)
                if not res:
                    logger.debug("card parse error")
                    time.sleep(1)
                    continue
                for loc in location:
                    logger.debug("loc={}".format(loc))
                    click(loc)
                    time.sleep(0.5)
                logger.debug('确认')
                click([634, 623])
                time.sleep(3)
                continue
            if detectImage(grey, 'end_round') and detectImage(grey, 'enter_round_2'):
                # logger.debug('结束回合')

                if detectImage(grey, 'give_up'):
                    logger.debug('投降')
                    click([639, 290])
                    time.sleep(3)
                    continue

                if giveUpFlag and (detectImage(grey, '01') or detectImage(grey, '02')):
                    logger.debug('等级过高,放弃这局比赛')
                    click([50, 50])
                    continue

                res, enemy_hp = get_enemy_hp(img)
                logger.debug('res : {} enemy_hp : {}'.format(res, enemy_hp))

                # if (detectImage(grey, '03') or detectImage(grey, '04')) and res and enemy_hp >= 28:
                #     logger.debug('进攻太慢,放弃这局比赛')
                #     click([50, 50])
                #     continue

                if detectImage(grey, '07') and res and enemy_hp >= 20:
                    logger.debug('进攻太慢,放弃这局比赛')
                    click([50, 50])
                    continue

                if detectImage(grey, '09'):
                    logger.debug('第九回合仍未结束比赛,自动放弃')
                    click([50, 50])
                    continue

                battleHandler.handleBattle(img, grey)
                continue

        else:
            time.sleep(0.4)
        logger.debug('------handle process end-------')


if __name__ == '__main__':
    test()
